package com.haidung.photojourney.activities;

import java.io.File;
import java.io.IOException;

import com.haidung.photojourney.R;
import com.haidung.photojourney.activities.based.LocationBasedActivity;
import com.haidung.photojourney.models.GoogleMapModel;
import com.haidung.photojourney.utils.LocationUtil;
import com.haidung.photojourney.utils.MediaUtil;
import com.haidung.photojourney.views.MainView;
import com.haidung.photojourney.vos.JourneyImage;
import com.haidung.photojourney.vos.JourneyMarker;

import android.location.Location;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

public class PhotoMapActivity extends LocationBasedActivity {
	private static final int CAMERA_ACTIVITY_REQUEST_CODE = 8000;
	private static final int PICTURE_ACTIVITY_REQUEST_CODE = 8001;

	private MainView view;
	private GoogleMapModel mapModel;
	public String[] allFiles;
	private static final String FILE_TYPE = "image/*";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		view = (MainView) View.inflate(this, R.layout.activity_main, null);
		view.setViewListener(viewListener);
		mapModel = GoogleMapModel.getInstance();
		mapModel.notifyInitMap();
		setContentView(view);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.action_take_geotagged_photo) {
			this.takeGeoTaggedPhoto();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		view.destroy();
	}

	File tempImageFile = null;

	private void takeGeoTaggedPhoto() {
		prepareLocationClient();
		createTempFile();

		if (tempImageFile != null) {
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempImageFile));
			startActivityForResult(cameraIntent, CAMERA_ACTIVITY_REQUEST_CODE);
		}
	}

	private void createTempFile() {
		File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/folderName");
		dir.mkdirs();

		if (dir.exists()) {
			try {
				tempImageFile = File.createTempFile("IMG_", ".jpg", dir);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private MainView.ViewListener viewListener = new MainView.ViewListener() {
		@Override
		public void showImageLocation() {
			PhotoMapActivity.this.startBrowseImage();
		}

		@Override
		public GoogleMap initMap() {
			GoogleMap googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
					.getMap();
			if (googleMap == null) {
				app.showLongTimeToast(getString(R.string.unable_create_map));
			}
			else{
			    mapModel.setClusterkraf(googleMap);
			}
			return googleMap;
		}
	};

	private void startBrowseImage() {
		Intent intent = new Intent();
		intent.setType(PhotoMapActivity.FILE_TYPE);
		intent.putExtra("return-data", true);
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select picture"), PICTURE_ACTIVITY_REQUEST_CODE);
	}

	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICTURE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                try {
                    Uri uri = Uri.parse(data.getDataString());
                    JourneyImage image = new JourneyImage(MediaUtil.getRealPath(getContentResolver(), uri))
                            .thumbnail(MediaUtil.getThumbnail(getContentResolver(), uri));

                    mapModel.addMarker(new JourneyMarker(image));
                } catch (Exception e) {
                }
            }
        } else if (requestCode == CAMERA_ACTIVITY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                Location location = getLastLocation();
                if (LocationUtil.isLocationValid(location)) {
                    try {
                        ExifInterface exif = new ExifInterface(tempImageFile.getAbsolutePath());
                        LocationUtil.geoTagged(location, exif);

                        Uri uri = MediaUtil.getImageContentUri(view.getContext(), tempImageFile);
                        JourneyImage image = new JourneyImage(tempImageFile.getAbsolutePath())
                                .thumbnail((MediaUtil.getThumbnail(getContentResolver(), uri)));

                        mapModel.addMarker(new JourneyMarker(image));
                        
                    } catch (Exception ex) {
                        Log.d(PhotoMapActivity.class.getName(), getString(R.string.error_geotag_photo), ex);
                        app.showLongTimeToast(getString(R.string.error_geotag_photo));
                    }
                } else {
                    app.showLongTimeToast("Location is out of dated.");
                }
            } else {
                app.showLongTimeToast(getString(R.string.unable_take_photo));
            }

            stopLocationClient();
        }
    }
}
